In [1]:
import matplotlib.pyplot as plt
import numpy as np
import random
import scipy as sp

# For presentation purposes only.
%matplotlib inline

Curve Fitting with SciPy

The SciPy library provides curve fitting functionality through the curve_fit function in the optimize module.


In [2]:
a, b, c = 5, 7, 13

# Generate noisy data.
x = np.linspace(-25, 25, 51, True)
noise = [random.uniform(-100, 100) for i in x]
y = (a*x**2+b*x+c) + noise

plt.scatter(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title("Noisy Parabola")
plt.grid()



In [3]:
from scipy.optimize import curve_fit

def f(x, a, b, c):
    return a*x**2+b*x+c

initial_guess = (7, 4, 15)
param_values, covar = curve_fit(f, x, y, initial_guess)
print(param_values)
print(covar)


[  4.98030364   7.64041883  14.20805775]
[[  1.81305151e-03   3.10838876e-10  -3.92827849e-01]
 [  3.10838876e-10   3.13899514e-01  -1.04436294e-07]
 [ -3.92827849e-01  -1.04436294e-07   1.53124243e+02]]

In [4]:
a, b, c = param_values

plt.scatter(x, y, marker='x')
plt.plot(x, f(x, a, b, c), c='r')
plt.xlabel('x')
plt.ylabel('y')
plt.title("Fitting Model to Data")


Out[4]:
<matplotlib.text.Text at 0x7fa1e2a6a2d0>